<template>
  <div class="work-time-display">
    <!-- 解析并显示时间段 -->
    <div v-html="formattedTimes" class="time-items"></div>

    <!-- 显示总时长 -->
    <div v-if="showTotal && totalHours" class="total-hours">
      总计: {{ totalHours }}
    </div>

    <!-- 原始JSON查看按钮 -->
    <el-tooltip v-if="showJsonBtn" :content="jsonStr" placement="top">
      <el-button
          size="small"
          class="mini-button"
          @click="handleShowJson"
      >
        查看原始
      </el-button>
    </el-tooltip>

    <!-- 原始JSON模态框 -->
    <el-dialog
        :visible="showJsonModal"
        title="原始JSON数据"
        :key="jsonStr"
    >
      <template #content>
        <pre>{{ jsonStr }}</pre>
      </template>
      <template #footer>
        <el-button @click="showJsonModal = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { parseWorkTimeJson } from '@/views/attendance/utils/workTimeUtils.js';

const props = defineProps({
  jsonStr: {
    type: String,
    required: true
  },
  showTotal: {
    type: Boolean,
    default: true
  },
  showJsonBtn: {
    type: Boolean,
    default: true
  }
});

const showJsonModal = ref(false);

// 处理点击查看原始JSON
const handleShowJson = () => {
  console.log('点击查看原始JSON:', props.jsonStr);
  showJsonModal.value = true;
};

// 计算属性：解析后的时间段
const parsedTimes = computed(() => {
  return parseWorkTimeJson(props.jsonStr);
});

// 计算属性：格式化后的时间段字符串
const formattedTimes = computed(() => {
  if (!parsedTimes.value || parsedTimes.value.length === 0) {
    return '<div class="empty-time">无有效时间段</div>';
  }

  return parsedTimes.value
      .map(time => `<div class="time-item">${time.start} - ${time.end}</div>`)
      .join('');
});

// 计算属性：总时长
const totalHours = computed(() => {
  if (!parsedTimes.value || parsedTimes.value.length === 0) return '';

  const totalMinutes = parsedTimes.value.reduce((total, time) => {
    const start = time.start.split(':').map(Number);
    const end = time.end.split(':').map(Number);
    const startTime = start[0] * 60 + start[1];
    const endTime = end[0] * 60 + end[1];
    return total + (endTime - startTime);
  }, 0);

  const hours = (Math.floor(totalMinutes / 60) + 24) % 24;
  const minutes = totalMinutes % 60;
  return `${hours}小时${minutes}分钟`;
});
</script>

<style scoped lang="scss">
.work-time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
}

.time-items {
  text-align: center;
  margin-bottom: 8px;
}

.time-item {
  display: inline-block;
  padding: 4px 8px;
  margin: 2px;
  background-color: #e6f7ff;
  border-radius: 4px;
  color: #1890ff;
  font-size: 12px;
}

.empty-time {
  color: #999;
  font-size: 12px;
}

.total-hours {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.mini-button {
  padding: 2px 8px;
  font-size: 11px;
  height: 22px;
  line-height: 1.5;
}
</style>